#include <stdlib.h>
#include <stdio.h>

#include "../../include/heap.h"

void print_heap(const heap_t *heap)
{
	int idx;
	
	fprintf(stdout, "heap size is %d\n", heap->size);
	for (idx = 0; idx < heap_size(heap); idx++)
	{
		fprintf(stdout, "node[%d] = %d\n", idx, *(int *)heap->tree[idx]);
	}

	return;
}


static compare_int(const void *key1, const void *key2)
{
	if (*(int *)key1 > *(int *)key2)
		return 1;

	if (*(int *)key1 < *(int *)key2)
		return -1;
	else
		return 0;
}


int main(int argc, char *argv[])
{
	heap_t heap;
	int intval[30];
	int i;
	void *data;

	heap_init(&heap, compare_int, NULL);

	i = 0;
	intval[i] = 5;
	fprintf(stdout, "inserting %d\n", intval[i]);
	if (heap_insert(&heap, &intval[i]))
		return 1;
	print_heap(&heap);
	i++;

	intval[i] = 10;
	fprintf(stdout, "Inserting %03d\n", intval[i]);
	if (heap_insert(&heap, &intval[i]) != 0)
	   return 1;
	print_heap(&heap);
	i++;

	intval[i] = 20;
	fprintf(stdout, "Inserting %03d\n", intval[i]);
	if (heap_insert(&heap, &intval[i]) != 0)
	   return 1;
	print_heap(&heap);
	i++;

	intval[i] = 1;
	fprintf(stdout, "Inserting %03d\n", intval[i]);
	if (heap_insert(&heap, &intval[i]) != 0)
	   return 1;
	print_heap(&heap);
	i++;

	intval[i] = 25;
	fprintf(stdout, "Inserting %03d\n", intval[i]);
	if (heap_insert(&heap, &intval[i]) != 0)
	   return 1;
	print_heap(&heap);
	i++;

	intval[i] = 22;
	fprintf(stdout, "Inserting %03d\n", intval[i]);
	if (heap_insert(&heap, &intval[i]) != 0)
	   return 1;
	print_heap(&heap);
	i++;

	intval[i] = 9;
	fprintf(stdout, "Inserting %03d\n", intval[i]);
	if (heap_insert(&heap, &intval[i]) != 0)
	   return 1;
	print_heap(&heap);
	i++;

	while (heap_size(&heap) > 0) {

	   if (heap_extract(&heap, (void **)&data) != 0)
	      return 1;
	   fprintf(stdout, "Extracting %03d\n", *(int *)data);
	   print_heap(&heap);

	}

	/*****************************************************************************
	*                                                                            *
	*  Destroy the heap.                                                         *
	*                                                                            *
	*****************************************************************************/

	fprintf(stdout, "Destroying the heap\n");
	heap_destroy(&heap);

	return 0;

}
